import { crypto } from './encrypt';

const config = {
    type: 'localStorage', // 本地存储类型 localStorage/sessionStorage
    prefix: 'capweb.v.1.0_', // 名称前缀 建议：项目名 + 项目版本
    expire: 24 * 60 * 60, // 默认过期时间 单位：秒
    isEncrypt: true, // 默认加密 为了调试方便, 开发过程中可以不加密
};
const { encrypt, decrypt } = crypto;

/**
 * storage缓存扩展
 */
const appStorage = config.type === 'localStorage' ? localStorage : sessionStorage;

export const AppStorageCache = {
    // 加入缓存
    put: function(key, stringVal, time = config.expire, storage = appStorage) {
        try {
            if (!storage) {
                return false;
            }
            if (!time || isNaN(time)) {
                time = config.expire; // 默认过期时间
            }
            const cacheExpireDate = new Date().getTime() - 1 + time * 1000;
            const cacheVal = {
                val: stringVal,
                exp: cacheExpireDate,
            };
            storage.setItem(config.prefix + key,
                config.isEncrypt ? encrypt(JSON.stringify(cacheVal)) : JSON.stringify(cacheVal)); // 存入缓存值
        } catch (e) {
            return null;
        }
    },
    // 获取缓存
    get: function(key, storage = appStorage) {
        try {
            if (!storage) {
                return false;
            }
            const cacheStr = storage.getItem(config.prefix + key);
            if (!cacheStr) {
                return null; // 缓存不存在
            }
            const cacheVal = decrypt(cacheStr);
            let result = {
                val: '',
            };
            try {
                result = JSON.parse(cacheVal);
            } catch (e) {
                // e
            }
            const now = new Date().getTime();
            if (typeof result !== 'object') {
                // 缓存信息不是通过该方法存储的
                return cacheVal;
            }
            if (result.exp && now > result.exp) {
                // 缓存过期
                this.remove(config.prefix + key);
                return '';
            }
            return config.isEncrypt ? result.val : result.val;
        } catch (e) {
            this.remove(config.prefix + key);
            return null;
        }
    },
    // 移除缓存，一般情况不手动调用，缓存过期自动调用
    remove: function(key, storage = appStorage) {
        if (!storage) {
            return false;
        }
        storage.removeItem(config.prefix + key);
    },
    // 清空所有缓存
    clear: function(storage = appStorage) {
        if (!storage) {
            return false;
        }
        storage.clear();
    },
};

export const AppCookie = {
    setCookie(cname, cvalue, exdays = 1, path) {
        const d = new Date();
        let expires = '';
        if (exdays) {
            d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
            expires = `expires=${d.toUTCString()}`;
        }
        if (path) {
            expires += expires ? '; path=/' : 'path=/';
        }
        document.cookie = `${config.prefix + cname}=${config.isEncrypt ? encrypt(cvalue) : cvalue}; ${expires}`;
    },
    getCookie(cname) {
        const name = `${config.prefix + cname}=`;
        const ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            const c = ca[i].trim();
            if (c.indexOf(name) === 0) {
                return config.isEncrypt ?
                    decrypt(c.substring(name.length, c.length)) :
                    c.substring(name.length, c.length);
            }
        }
        return '';
    },
};
